#include "GxWinClipBoard.h"

#include "Windows.h"

namespace GxWinGUI
{
	void ClipBoard::SetText(const String & text)
	{
		if (!OpenClipboard(Application::GetMainFormHandle())) 
			return; 
		String t = text;
		for (int i=0; i<t.GetLength(); i++)
			if (t[i] == L'\n')
			{
				t.Insert(L'\r',i);
				i++;
			}
		// Allocate a global memory object for the text. 
 
        HGLOBAL hglbCopy = GlobalAlloc(GMEM_MOVEABLE, (t.GetLength()+1)*sizeof(wchar_t)); 
        if (hglbCopy == NULL) 
        { 
            CloseClipboard(); 
            return;
        } 
		EmptyClipboard();
        // Lock the handle and copy the text to the buffer. 
        wchar_t * lptstrCopy = (wchar_t *)GlobalLock(hglbCopy); 
		memcpy(lptstrCopy, t.GetStrPtr(), (t.GetLength()+1)*sizeof(wchar_t)); 
        GlobalUnlock(hglbCopy); 
		SetClipboardData(CF_UNICODETEXT, hglbCopy); 
		CloseClipboard();
	}

	String ClipBoard::GetText()
	{
		String rs;
		if (!IsClipboardFormatAvailable(CF_UNICODETEXT)) 
            return rs; 
		if (!OpenClipboard(Application::GetMainFormHandle())) 
            return rs; 
		HANDLE hglb = GetClipboardData(CF_UNICODETEXT); 
        if (hglb != NULL) 
        { 
            wchar_t * lptstr = (wchar_t *)GlobalLock(hglb); 
            if (lptstr != NULL) 
            { 
                // Call the application-defined ReplaceSelection 
                // function to insert the text and repaint the 
                // window. 
 
                rs = lptstr;
                GlobalUnlock(hglb); 
            } 
        } 
		CloseClipboard();
		return rs;
	}
}